package org.xiaoleng.cdm.divers;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

@Slf4j
public class DriverLoader {

    public static void load(String driverPath, String driverName) {
        //
        URLClassLoader classLoader = null;
        try {
            ClassPathResource resource = new ClassPathResource(driverPath);
            classLoader = URLClassLoader.newInstance(
                    new URL[]{resource.getURL()},
                    null // 这里传入null意味着没有父类加载器，或者使用当前线程的上下文类加载器
            );
            Class.forName(driverName);
            log.info("load mysql driver successfully.");
        } catch (ClassNotFoundException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (classLoader != null) {
                    classLoader.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        DriverLoader.load("classpath:drivers/mysql-connector-java-8.0.27.jar", "com.mysql.cj.jdbc.Driver");
    }
}
